﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using ZX.BLL.Extend;
using ZX.Web.UI.Controls;
using ZX.Common;
using System.Collections;
using System.Collections.Generic;
using ZX.DAL.DBExtend;
using ZX.DBModule;
using System.Data.SqlClient;
using System.Data;
using ZX.BLL;
using ZX.SYS.Bussiness.Message;
using ZX.SYS.Library;
using ZX.Common.Extend;
using Newtonsoft.Json;
using System.Text.RegularExpressions;


namespace DCBH.Web
{
    public partial class DCBHCommonOperator : BasePage
    {
        private string actionStr = string.Empty;
        
        protected void Page_Load(object sender, EventArgs e)
        {
            if (this.UserId == null)
            {
                Response.Write("因长时间不操作系统，用户相关信息失效，请退出重新登录！");
                return;
            }

            actionStr = this.GetStringFromQueryString("Action","");

            string strEntity = this.GetStringFromQueryString("entity", "E_Menu");
            string flag = this.GetStringFromQueryString("flag", "");
            string strType = this.GetStringFromQueryString("type", "");
            string strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
            string strDataAction = this.GetStringFromQueryString("dataAction", "");
                        
            switch (actionStr)
            {
                case "gennewsequenceno":
                    GenNewSequenceNo();
                    break;
                case "delete":
                    RunDelete(strEntity, strJson);
                    break;
                case "procedure":
                    RunProcedure(strEntity, strDataAction);
                    break;
                case "update":
                    RunUpdate(strEntity, strJson);
                    break;
                case "check":
                    RunCheck(strEntity, strJson);
                    break;
                default:
                    break;
            }
        }

        private void RunCheck(string strEntity, string strJson)
        {
            switch (strEntity)
            {
                case "GetItemData":
                    GetItemData(strJson);
                    break;
                default:
                    break;
            }
        }

        private void GetItemData(string itemNo)
        {
            itemNo = this.GetStringFromQueryString("id", "");

            DbSql db = new DbSql();
            string strSql = string.Format("select ItemNo, ItemModel, ItemName from BH_ItemMaster where ItemNo = '{0}'", itemNo);
            DataTable dt = db.ExecuteQuery(strSql);
            string str = Globals.DataTableToJSON(dt);
            HttpContext.Current.Response.Write(str);
        }

        /// <summary>
        /// 自定义删除方法
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void RunDelete(string strEntity, string strJson)
        {
            switch (strEntity)
            {
                default:
                    break;
            }
        }

        /// <summary>
        /// 自定义修改方法
        /// </summary>
        /// <param name="strEntity"></param>
        /// <param name="strJson"></param>
        private void RunUpdate(string strEntity, string strJson)
        {
            switch (strEntity)
            {
                
                default:
                    break;
            }
        }

        /// <summary>
        /// 自定义保存方法，执行存储过程
        /// </summary>
        /// <param name="strEntity">实体</param>
        /// <param name="strJson">JSON数据</param>
        /// <param name="strAction">动作</param>
        private void RunProcedure(string strEntity, string strDataAction)
        {
            string strJson = this.GetStringFromQueryString("json", "").Replace("[@@]", "\\");
            string strDetailJson = this.GetStringFromQueryString("detailjson", "").Replace("[@@]", "\\");

            switch (strEntity)
            {
                case "V_BH_BOM":
                    ExecProcedure("Usp_BH_BOM", strJson, strDetailJson, strDataAction); 
                    break;
                case "BH_ItemMaster":
                    ExecProcedure("Usp_BH_ItemMaster", strJson, "", strDataAction);
                    break;
                case "V_BH_PurchaseOrder":      // 部品采购订单
                    ExecProcedure("Usp_BH_PurchaseOrder", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_SalesOrder":         // 成品销售订单
                    ExecProcedure("Usp_BH_SalesOrder", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_WorkOrder":          // 生产指示
                    ExecProcedure("Usp_BH_WorkOrder", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_InsYarns":           // 部品入库
                    ExecProcedure("Usp_BH_InsYarns", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_InsGreigeCloth":     // 半成品入库
                    ExecProcedure("Usp_BH_InsGreigeCloth", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_InsProduct":         // 成品入库
                    ExecProcedure("Usp_BH_InsProduct", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_OutsProduct":        // 成品出库
                    ExecProcedure("Usp_BH_OutsProduct", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_AccountsReceivableDetail":                        // 手工录入应收明细
                    ExecProcedure("Usp_BH_AccountsReceivableDetail", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_AccountsPayableDetail":                           // 手工录入应付明细
                    ExecProcedure("Usp_BH_AccountsPayableDetail", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_AccountsReceivable": // 应收结算
                    string aRInitFlag = this.GetStringFromQueryString("initFlag", "").Replace("[@@]", "\\");
                    string jsonDataAR = this.GetStringFromQueryString("jsonData", "").Replace("[@@]", "\\");
                    string detailIDListAR = this.GetStringFromQueryString("detailIDList", "").Replace("[@@]", "\\");

                    ExecProAPAR(1, Convert.ToInt16(aRInitFlag), jsonDataAR, detailIDListAR);

                    break;
                case "V_BH_AccountsPayable":    // 应付结算
                    string aPInitFlag = this.GetStringFromQueryString("initFlag", "").Replace("[@@]", "\\");
                    string jsonDataAP = this.GetStringFromQueryString("jsonData", "").Replace("[@@]", "\\");
                    string detailIDListAP = this.GetStringFromQueryString("detailIDList", "").Replace("[@@]", "\\");

                    ExecProAPAR(0, Convert.ToInt16(aPInitFlag), jsonDataAP, detailIDListAP);

                    break;
                case "V_BH_Receipts":           // 收款单
                    ExecProcedure("Usp_BH_Receipts", strJson, strDetailJson, strDataAction);
                    break;
                case "V_BH_Payment":            // 付款单
                    ExecProcedure("Usp_BH_Payment", strJson, strDetailJson, strDataAction);
                    break;
                default:
                    break;
            }
        }

        private void ExecProcedure(string procedureName, string strJson, string strDetailJson, string strAction)
        {
            //BaseBussnies blls = new BaseBussnies();
            try
            {
                int iResult = 0;
                DbSql dbSql = new DbSql();

                SqlParameter action = new SqlParameter("@Action", SqlDbType.Char, 1);
                action.Direction = ParameterDirection.Input;
                action.Value = strAction;

                SqlParameter jsonData = new SqlParameter("@JsonData", SqlDbType.NVarChar, 8000);
                jsonData.Direction = ParameterDirection.Input;
                jsonData.Value = strJson;

                SqlParameter returnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 100);
                returnValue.Direction = ParameterDirection.Output;
                returnValue.Value = "";

                IDataParameter[] parameters;

                if (strDetailJson != null && strDetailJson != "")
                {
                    SqlParameter detailJson = new SqlParameter("@DetailJsonData", SqlDbType.NVarChar, 8000);
                    detailJson.Direction = ParameterDirection.Input;
                    detailJson.Value = strDetailJson;

                    parameters = new IDataParameter[] { action, jsonData, detailJson, returnValue };
                }
                else
                {
                    parameters = new IDataParameter[] { action, jsonData, returnValue };
                } 

                string strSql = dbSql.RunProcedureReturnString(procedureName, parameters, out iResult);

                if (strSql == "1" || strSql == "")
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write(strSql);
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.ToString());
            }
        }

        // 应收应付结算
        private void ExecProAPAR(int rpFlag, int initFlag, string strJson, string strdetailIDList)
        {
            //BaseBussnies blls = new BaseBussnies();
            try
            {
                int iResult = 0;
                DbSql dbSql = new DbSql();

                SqlParameter flag = new SqlParameter("@Flag", SqlDbType.Bit);
                flag.Direction = ParameterDirection.Input;
                flag.Value = rpFlag;

                SqlParameter isInit = new SqlParameter("@IsInit", SqlDbType.Bit);
                isInit.Direction = ParameterDirection.Input;
                isInit.Value = initFlag;

                SqlParameter jsonData = new SqlParameter("@JsonData", SqlDbType.NVarChar, 8000);
                jsonData.Direction = ParameterDirection.Input;
                jsonData.Value = strJson;

                SqlParameter detailIDList = new SqlParameter("@DetailIDList", SqlDbType.NVarChar, 8000);
                detailIDList.Direction = ParameterDirection.Input;
                detailIDList.Value = strdetailIDList;

                SqlParameter returnValue = new SqlParameter("@ReturnValue", SqlDbType.NVarChar, 500);
                returnValue.Direction = ParameterDirection.Output;
                returnValue.Value = "";

                IDataParameter[] parameters;
                parameters = new IDataParameter[] { flag, isInit, jsonData, detailIDList, returnValue };

                string strSql = dbSql.RunProcedureReturnString("Usp_BH_APAndAR", parameters, out iResult);

                if (strSql == "1" || strSql == "")
                {
                    HttpContext.Current.Response.Write("1");
                }
                else
                {
                    HttpContext.Current.Response.Write(strSql);
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.ToString());
            }
        }

        // 生成新的编号
        private void GenNewSequenceNo()
        {
            string json = string.Format("{{\"Staute\":\"Error\",\"Msg\":\"处理失败\"}}");
            try
            {
                string sequenceName = this.GetStringFromQueryString("SequenceName", "");

                if (string.IsNullOrEmpty(sequenceName))
                {
                    json = string.Format("{{\"Staute\":\"Success\",\"Msg\":\"{0}\"}}", Guid.NewGuid());
                }
                else
                {
                    string code = IDMaker.GetSequenceStr(sequenceName);
                    json = string.Format("{{\"Staute\":\"Success\",\"Msg\":\"{0}\"}}", code);
                }
                Response.Clear();
                Response.Write(json);
                Response.End();
            }
            catch (Exception ex)
            {
                json = string.Format("{{\"Staute\":\"Error\",\"Msg\":\"{0}\"}}", ex.Message);
            }
            Response.Clear();
            Response.Write(json);
            Response.End();
        }
    }
}